<template>
  <view class="container">
    <!-- 导入方式选择 -->
    <view class="import-methods">
      <view class="method-title">选择导入方式</view>
      
      <!-- 文本输入导入 -->
      <view class="method-card" @click="showTextInput = true">
        <view class="method-icon">
          <u-icon name="edit-pen" size="40" color="#007aff"></u-icon>
        </view>
        <view class="method-content">
          <text class="method-name">文本输入</text>
          <text class="method-desc">直接输入或粘贴文本内容</text>
        </view>
        <u-icon name="arrow-right" size="24" color="#999"></u-icon>
      </view>
      
      <!-- 文件选择导入 -->
      <view class="method-card" @click="chooseFile">
        <view class="method-icon">
          <u-icon name="file-text" size="40" color="#34c759"></u-icon>
        </view>
        <view class="method-content">
          <text class="method-name">文件选择</text>
          <text class="method-desc">选择本地文本文件</text>
        </view>
        <u-icon name="arrow-right" size="24" color="#999"></u-icon>
      </view>
    </view>

    <!-- 最近导入的书籍 -->
    <view v-if="recentBooks.length > 0" class="recent-books">
      <view class="section-title">最近导入</view>
      <view class="book-list">
        <view 
          v-for="(book, index) in recentBooks" 
          :key="index"
          class="recent-book-item"
          @click="openBook(book)"
        >
          <u-image
            :src="book.cover || '/static/default-cover.png'"
            width="60px"
            height="80px"
            mode="aspectFill"
          ></u-image>
          <view class="book-details">
            <text class="book-title">{{ book.title }}</text>
            <text class="book-info">{{ book.wordCount }}字 · {{ book.importTime }}</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 文本输入弹窗 -->
    <u-popup v-model="showTextInput" mode="center" width="90%" height="80%">
      <view class="text-input-popup">
        <view class="popup-header">
          <text class="popup-title">输入书籍信息</text>
          <u-icon name="close" size="24" @click="showTextInput = false"></u-icon>
        </view>
        
        <view class="input-form">
          <view class="form-item">
            <text class="form-label">书名</text>
            <u-input 
              v-model="bookForm.title" 
              placeholder="请输入书名"
              border="surround"
            ></u-input>
          </view>
          
          <view class="form-item">
            <text class="form-label">作者</text>
            <u-input 
              v-model="bookForm.author" 
              placeholder="请输入作者（可选）"
              border="surround"
            ></u-input>
          </view>
          
          <view class="form-item">
            <text class="form-label">内容</text>
            <textarea
              v-model="bookForm.content"
              class="content-textarea"
              placeholder="请输入或粘贴书籍内容"
              :maxlength="1000000"
              style="min-height: 300rpx; width: 100%; border: 1px solid #e0e0e0; border-radius: 8rpx; padding: 20rpx; box-sizing: border-box;"
            ></textarea>
          </view>
        </view>
        
        <view class="popup-actions">
          <u-button @click="showTextInput = false">取消</u-button>
          <u-button type="primary" @click="importFromText">导入</u-button>
        </view>
      </view>
    </u-popup>

    <!-- 自定义底部导航（list模式） -->
    <u-tabbar v-model="current" :list="tabBarList" :fixed="true" :placeholder="true" @change="onTabChange" />
  </view>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { onShow } from '@dcloudio/uni-app';

// 隐藏原生tabbar
onMounted(() => {
  uni.hideTabBar({ animation: false });
});
// 页面展示时同步高亮
const current = ref(1);
onShow(() => {
  uni.hideTabBar({ animation: false });
  current.value = 1;
});

// 自定义tabbar配置
const tabBarList = ref([
  { iconPath: 'home', selectedIconPath: 'home-fill', text: '首页' },
  { iconPath: 'plus', selectedIconPath: 'plus', text: '导入', midButton: false },
  { iconPath: 'account', selectedIconPath: 'account-fill', text: '我的' }
]);

// 响应式数据
const showTextInput = ref(false);
const recentBooks = ref([]);
const bookForm = ref({
  title: '',
  author: '',
  content: ''
});

// 选择文件
const chooseFile = () => {
  // #ifdef H5
  const input = document.createElement('input');
  input.type = 'file';
  input.accept = '.txt,.md,.doc,.docx';
  input.onchange = (e) => {
    const file = e.target.files[0];
    if (file) {
      readFile(file);
    }
  };
  input.click();
  // #endif
  
  // #ifdef APP-PLUS
  uni.chooseFile({
    count: 1,
    type: 'file',
    extension: ['.txt', '.md', '.doc', '.docx'],
    success: (res) => {
      const filePath = res.tempFilePaths[0];
      readFileFromPath(filePath);
    }
  });
  // #endif
};

// 读取文件内容
const readFile = (file) => {
  const reader = new FileReader();
  reader.onload = (e) => {
    const content = e.target.result;
    bookForm.value.content = content;
    bookForm.value.title = file.name.replace(/\.[^/.]+$/, '');
    showTextInput.value = true;
  };
  reader.readAsText(file);
};

// 从路径读取文件（APP环境）
const readFileFromPath = (filePath) => {
  uni.getFileSystemManager().readFile({
    filePath: filePath,
    encoding: 'utf8',
    success: (res) => {
      const fileName = filePath.split('/').pop();
      bookForm.value.content = res.data;
      bookForm.value.title = fileName.replace(/\.[^/.]+$/, '');
      showTextInput.value = true;
    },
    fail: () => {
      uni.showToast({ title: '读取文件失败', icon: 'none' });
    }
  });
};

// 从文本导入
const importFromText = () => {
  if (!bookForm.value.title.trim()) {
    uni.showToast({ title: '请输入书名', icon: 'none' });
    return;
  }
  if (!bookForm.value.content.trim()) {
    uni.showToast({ title: '请输入书籍内容', icon: 'none' });
    return;
  }
  const book = {
    id: Date.now().toString(),
    title: bookForm.value.title.trim(),
    author: bookForm.value.author.trim() || '未知作者',
    content: bookForm.value.content.trim(),
    wordCount: bookForm.value.content.trim().length,
    importTime: new Date().toLocaleDateString(),
    progress: 0,
    cover: '/static/default-cover.png'
  };
  try {
    const existingBooks = uni.getStorageSync('books') || [];
    existingBooks.unshift(book);
    uni.setStorageSync('books', existingBooks);
    showTextInput.value = false;
    bookForm.value = { title: '', author: '', content: '' };
    uni.showToast({ title: '导入成功', icon: 'success' });
    uni.$emit('booksUpdated');
    setTimeout(() => {
      uni.switchTab({ url: '/pages/index/index' });
    }, 1200);
  } catch (e) {
    uni.showToast({ title: '保存失败', icon: 'none' });
  }
};

// 打开书籍
const openBook = (book) => {
  uni.navigateTo({ url: `/pages/reader/reader?id=${book.id}&title=${encodeURIComponent(book.title)}` });
};

// 页面加载时获取最近导入的书籍
onMounted(() => {
  try {
    const allBooks = uni.getStorageSync('books') || [];
    recentBooks.value = allBooks.slice(0, 5);
  } catch (e) {
    recentBooks.value = [];
  }
});

// 自定义tabbar切换
const onTabChange = (index) => {
  current.value = index;
  if (index === 0) {
    uni.switchTab({ url: '/pages/index/index' });
  } else if (index === 1) {
    // 当前页
  } else if (index === 2) {
    uni.switchTab({ url: '/pages/myInfo/myInfo' });
  }
};
</script>

<style lang="scss" scoped>
.container {
  padding: 20rpx;
  padding-bottom: 140rpx; // 预留自定义tabbar空间
  background-color: #f5f5f5;
  min-height: 100vh;
}

.import-methods {
  background: white;
  border-radius: 16rpx;
  padding: 30rpx;
  margin-bottom: 30rpx;
  
  .method-title {
    font-size: 32rpx;
    font-weight: bold;
    color: #333;
    margin-bottom: 30rpx;
  }
}

.method-card {
  display: flex;
  align-items: center;
  padding: 30rpx;
  border: 2rpx solid #f0f0f0;
  border-radius: 12rpx;
  margin-bottom: 20rpx;
  transition: all 0.3s ease;
  
  &:active {
    background-color: #f8f8f8;
    border-color: #007aff;
  }
  
  .method-icon {
    margin-right: 20rpx;
  }
  
  .method-content {
    flex: 1;
    
    .method-name {
      display: block;
      font-size: 30rpx;
      font-weight: bold;
      color: #333;
      margin-bottom: 8rpx;
    }
    
    .method-desc {
      display: block;
      font-size: 24rpx;
      color: #999;
    }
  }
}

.recent-books {
  background: white;
  border-radius: 16rpx;
  padding: 30rpx;
  
  .section-title {
    font-size: 32rpx;
    font-weight: bold;
    color: #333;
    margin-bottom: 20rpx;
  }
}

.book-list {
  .recent-book-item {
    display: flex;
    align-items: center;
    padding: 20rpx 0;
    border-bottom: 1rpx solid #f0f0f0;
    
    &:last-child {
      border-bottom: none;
    }
    
    .book-details {
      flex: 1;
      margin-left: 20rpx;
      
      .book-title {
        display: block;
        font-size: 28rpx;
        font-weight: bold;
        color: #333;
        margin-bottom: 8rpx;
      }
      
      .book-info {
        display: block;
        font-size: 24rpx;
        color: #999;
      }
    }
  }
}

.text-input-popup {
  background: white;
  border-radius: 16rpx;
  padding: 30rpx;
  
  .popup-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 30rpx;
    
    .popup-title {
      font-size: 32rpx;
      font-weight: bold;
      color: #333;
    }
  }
  
  .input-form {
    margin-bottom: 30rpx;
    
    .form-item {
      margin-bottom: 20rpx;
      
      .form-label {
        display: block;
        font-size: 28rpx;
        color: #333;
        margin-bottom: 10rpx;
      }
    }
  }
  
  .popup-actions {
    display: flex;
    gap: 20rpx;
    
    .u-button {
      flex: 1;
    }
  }
}

.content-textarea {
  font-size: 28rpx;
  line-height: 1.6;
  resize: none;
}
</style>
